package poem_info2.JdbcUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.jdbc.core.JdbcTemplate;
import poem_info2.Task.Task3;
import poem_info2.domain.Id;
import poem_info2.domain.Poem3;

import java.net.URL;
import java.util.List;

/**
 * https://www.gushiwen.com/type/n/xianqin/n/n.html
 * 古诗文网 爬取古籍 解析详情页
 */
/*解析每一首古诗页面的详情信息并保存*/
public class ParseDetailedUrl3 {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    public void parseUrl(String purl, List<Poem3> ps) throws Exception {
        String content = "";
        String title = "";
        String dynasty = "";
        String writer = "";
        //创建poem对象
        Poem3 p = new Poem3();
        //定义sql
        String sql = "insert into poems values(null, ?, ?, ?, ?, ?)";
        //创建id对象
        Id id = new Id();
        //解析详情页url
        Document document = null;
        try {
            document = Jsoup.parse(new URL(purl), 100000);
            //title
            title = document.select("#main > h1").text();
            p.setTitle(title);
            //dynasty_id
            dynasty = document.select("#main > div.p10.lh180 > div:nth-child(1) > p:nth-child(1)")
                    .text().split("：")[1];
            Integer dynasty_id = id.getId(dynasty, 2);
            p.setDynasty_id(dynasty_id);
            //writer_id
            writer = document.select("#main > div.p10.lh180 > div:nth-child(1) > p:nth-child(2)")
                    .text();
            if (writer.equals("作者：")) {
                writer = document.select("#main > div.p10.lh180 > div:nth-child(1) > p:nth-child(2) > a").text();
            } else {
                writer = writer.split("：")[1];
            }
            Integer writer_id = id.getId(writer, 1);
            p.setWriter_id(writer_id);
            //content
            content = document.select("div.view").text();
//            System.out.println(title + "/" + dynasty + "/" + writer + "/" + content);
            //判断该poem对象是否已经存在
            boolean flag = false;
            for (Poem3 poem : ps) {
                if (poem.equals(p)) {
                    flag = true;
                }
            }
            //如果存在
            if (flag) {
                Task3.existed++;
            } else {//如果不存在
                //存储数据
                template.update(sql, p.getTitle(), p.getDynasty_id(), p.getWriter_id(), content, purl);
                System.out.println("[" + Task3.count++ + "]" + p.getTitle() + " " + purl + "已保存！");
                Task3.reserved++;
                ps.add(p);
            }
        } catch (Exception e) {
            template.update("insert into exception values (null , ?, ?)", p.getTitle() + "/"
                    + p.getDynasty_id() + "/" + p.getWriter_id() + "/" + content, purl);
            Task3.exception_count++;
        }
    }
}
